//
//  UITableView+Ext.swift
//  TTCOM-iOS
//
//  Created by Toj on 3/1/23.
//

import Foundation

public extension UITableView {
    
    func setScrollToTop(animated: Bool) {
        setContentOffset(.zero, animated: animated)
    }
    
    func stopScroll() { 
        setContentOffset(contentOffset, animated: false)
    }

    func scrollToTopRow(animated: Bool) {
        let sections = numberOfSections
        guard sections > 0 else { return }
        let section = sections - 1
        let rows = numberOfRows(inSection: section)
        guard rows > 0 else { return }
        let indexPath = IndexPath(row: 0, section: 0)
        scrollToRow(at: indexPath, at: .top, animated: animated)
    }
    
    func scrollToBottomRow(animated: Bool) {
        let sections = numberOfSections
        guard sections > 0 else { return }
        let section = sections - 1
        let rows = numberOfRows(inSection: section)
        guard rows > 0 else { return }
        let row = rows - 1
        let indexPath = IndexPath(row: row, section: section)
        scrollToRow(at: indexPath, at: .bottom, animated: animated)
    }
}

public extension UITableView {
    
    /// 注册 Cell
    func register<T: UITableViewCell>(cellClass T: T.Type) {
        register(T.cell_class, forCellReuseIdentifier: T.cell_identifier)
    }
    
    /// 复用 Cell
    func dequeueReusableCell<T: UITableViewCell>(withReuseIdentifierClass T: T.Type) -> T {
        var cell = dequeueReusableCell(withIdentifier: T.cell_identifier) as? T
        if cell == nil {
            cell = T.init(style: .default, reuseIdentifier: T.cell_identifier)
        }
        return cell!
    }
    
    /// 获取 Cell
    func cellForItem<T: UITableViewCell>(at indexPath: IndexPath, convertTo T: T.Type) -> T? {
        let cell = cellForRow(at: indexPath) as? T
        return cell
    }
}

public extension UITableView {
    
    /// 注册 HeaderFooterView
    func register<T: UITableViewHeaderFooterView>(viewClass T: T.Type) {
        register(T.cell_class, forHeaderFooterViewReuseIdentifier: T.cell_identifier)
    }
    
    /// 复用 HeaderFooterView
    func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withIdentifierClass T: T.Type) -> T {
        var view = dequeueReusableHeaderFooterView(withIdentifier: T.cell_identifier) as? T
        if view == nil {
            view = T.init(reuseIdentifier: T.cell_identifier)
        }
        return view!
    }
    
    /// 获取 HeaderView
    func headerView<T: UITableViewHeaderFooterView>(forSection section: Int, convertTo T: T.Type) -> T? {
        let view = headerView(forSection: section) as? T
        return view
    }
    
    /// 获取 FooterView
    func footerView<T: UITableViewHeaderFooterView>(forSection section: Int, convertTo T: T.Type) -> UITableViewHeaderFooterView? {
        let view = footerView(forSection: section) as? T
        return view
    }
}
